import React from "react";
import { Button, Form, Input,InputNumber, Modal, message,Upload } from "antd";
import styles from '../index.less'
import { formDictionaryDownload, formDictionaryExport, formDictionaryImport, formDictionaryInfo, formDictionaryUpdate } from "@/services/formInteraction";
import UserSession from "@/UserSession";
import { history, Link } from "umi";
const testData = [
  {
      "r": 0,
      "c": 0,
      "v": {
          "m": "表头1",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "表头1"
      }
  },
  {
      "r": 0,
      "c": 1,
      "v": {
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "v": "22222222",
          "m": "22222222"
      }
  },
  {
      "r": 0,
      "c": 2,
      "v": {
          "m": "表头3",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "表头3"
      }
  },
  {
      "r": 0,
      "c": 8,
      "v": {
          "m": "表头4",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "表头4"
      }
  },
  {
      "r": 1,
      "c": 0,
      "v": {
          "m": "1-1",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "1-1"
      }
  },
  {
      "r": 1,
      "c": 1,
      "v": {
          "m": "2-1",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "2-1"
      }
  },
  {
      "r": 1,
      "c": 2,
      "v": {
          "m": "3-1",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "3-1"
      }
  },
  {
      "r": 1,
      "c": 8,
      "v": {
          "m": "3-1",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "3-1"
      }
  },
  {
      "r": 2,
      "c": 0,
      "v": {
          "m": "1-2",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "1-2"
      }
  },
  {
      "r": 2,
      "c": 1,
      "v": {
          "m": "2-2",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "2-2"
      }
  },
  {
      "r": 2,
      "c": 3,
      "v": {
          "v": "4444444",
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "m": "4444444"
      }
  },
  {
      "r": 3,
      "c": 0,
      "v": {
          "v": "4444444",
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "m": "4444444"
      }
  },
  {
      "r": 3,
      "c": 1,
      "v": {
          "m": "2-3",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "2-3"
      }
  },
  {
      "r": 4,
      "c": 1,
      "v": {
          "v": " 4344443",
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "m": " 4344443"
      }
  },
  {
      "r": 4,
      "c": 2,
      "v": {
          "v": "666",
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "m": "666"
      }
  },
  {
      "r": 7,
      "c": 8,
      "v": {
          "m": "3-7",
          "ct": {
              "fa": "General",
              "t": "g"
          },
          "v": "3-7"
      }
  },
  {
      "r": 12,
      "c": 2,
      "v": {
          "v": "333",
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "m": "333"
      }
  },
  {
      "r": 12,
      "c": 8,
      "v": {
          "v": "6",
          "ct": {
              "fa": "General",
              "t": "n"
          },
          "m": "6"
      }
  }
]
class DictionaryEdit extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      name:"",
      comment:"",
      columns:[],
      data:[],
      beforeValue:1,
      afterValue:1,
      insertInfo:{
        num:1,
        type:"",
        visible:false,
        y:'',
        title:""
      },
      importVisible:false,
      importLoading:false
    }
    
  }

  componentDidMount(){
    this.getDetail()
  }

  getDetail = async () => {
    let data = []

    const { location:{query:{dictionaryId}},form:{setFieldsValue} } = this.props
    if(dictionaryId){
      const res = await formDictionaryInfo({id:dictionaryId})
      data = res.data ? res.data : []
      setFieldsValue({name:res.name,remark:res.remark})
    }
    console.log(data);
    this.createLuckysheet(data)
  }

  createLuckysheet = (data) => {
    var options = {
      container: 'luckysheet',//容器id
      title: '', // 设定表格名称
      lang: 'zh', // 设定表格语言
      showtoolbar:false,//自定义工具栏
      showinfobar:false,//头部信息栏
      showsheetbar:false,//底部sheet页
      sheetFormulaBar:false,//是否显示公式栏
      data:[
        {
          index:0,
          order:0,
          name:"Sheet1",
          celldata:data
        }
      ],
      cellRightClickConfig:{
        copy: false, // 复制
        copyAs: false, // 复制为
        paste: false, // 粘贴
        insertRow: true, // 插入行
        insertColumn: true, // 插入列
        deleteRow: true, // 删除选中行
        deleteColumn: true, // 删除选中列
        deleteCell: true, // 删除单元格
        hideRow: false, // 隐藏选中行和显示选中行
        hideColumn: false, // 隐藏选中列和显示选中列
        rowHeight: false, // 行高
        columnWidth: false, // 列宽
        clear: false, // 清除内容
        matrix: false, // 矩阵操作选区
        sort: false, // 排序选区
        filter: false, // 筛选选区
        chart: false, // 图表生成
        image: false, // 插入图片
        link: false, // 插入链接
        data: false, // 数据验证
      cellFormat: false // 设置单元格格式
      }
    }
    luckysheet.create(options)
  }

  saveValidate = () => {
    const { form:{validateFields} } = this.props;
    
    validateFields((error,values) => {
      if(!error){
        luckysheet.exitEditMode()
        const data = luckysheet.getcellvalue()
        let newData = []
        for(let i =0;i<data.length;i++){
          for(let j=0;j<data[i].length;j++){
            const item = data[i][j]
            if(item != null && item != undefined && item != '' && item.m != null && item.m != undefined && item.m != ''){
              newData.push({
                r:i,
                c:j,
                v:item
              })
            }
          }
        }
        this.doSave(values,newData)
      }
    })
  }

  doSave = async (values,data) => {
    const { location: { pathname, query }} = this.props;
    const res = await formDictionaryUpdate({...values,data,formId:query.id,id:query.dictionaryId})
    message.info(res.message)
    if(res.code == -1){

    }else{
      const { match: { url, params: { id }, }, location: { pathname, query }, children, route ,history} = this.props;
      let rootRouter = UserSession.isSystemKnowledge() ? 'systemKnowledge' : 'myKnowledge'
      let path =  "/knowledgeDesign/"+rootRouter+"/" + id + "/formInteraction/edit/dictionary"
      let params = query;
      history.push({ pathname: path,query:params })
    }
  }

  doExport = async () => {
    const { location: { pathname, query }} = this.props;
    const res = await formDictionaryExport({dicId:query.dictionaryId})
  }

  handleUpFile = async (info) => {
    this.setState({
      importLoading:true
    },() => {
      const { location: { pathname, query }} = this.props;
      const file = info.file
      if(file.status == 'done' && file.response){
        const response = file.response
        if(response.code == 0){
          this.createLuckysheet(response.data)
          this.cancelImportModal()
        }
        message.info(response.message)
        this.setState({
          importLoading:false
        })
      }
    })
    
  }

  componentWillUnmount(){
    if(luckysheet){
      luckysheet.exitEditMode()
    }
    
  }

  openImportModal = () => {
    this.setState({
      importVisible:true
    })
  }

  cancelImportModal = () => {
    this.setState({
      importVisible:false,
      importLoading:false
    })
  }

  downloadTemplate = async () => {
    const res = await formDictionaryDownload()
  }

  render(){
    const { data,name,comment,columns,insertInfo,importVisible,importLoading } = this.state;
    const { form:{ getFieldDecorator },location: { pathname, query },match: { url, params: { id }, } } = this.props;
    const importProps = {
			accept: ".xlsx,.xls",
			onChange: this.handleUpFile,
      showUploadList:false,
      action:"/cloud/form/dictionary/import",
      headers:{
        'Authorization':`Bearer ${UserSession.getToken()}`
      }
		};

    return (
      <div>
        <Form layout="inline">
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24}}>
            <div>
              <Form.Item label="名称">
                {
                  getFieldDecorator("name",{rules:[{required:true,message:"请输入名称"}]})(
                    <Input placeholder="请输入名称" />
                  )
                }
              </Form.Item>
              <Form.Item label="描述">
                {
                  getFieldDecorator("remark")(
                    <Input placeholder="请输入描述" />
                  )
                }
              </Form.Item>
            </div>
            <div>
              <Link 
                to={{ pathname: 
                  pathname.indexOf("systemKnowledge") > -1 ? 
                  "/knowledgeDesign/systemKnowledge/" + id + "/formInteraction/edit/dictionary" : 
                  "/knowledgeDesign/myKnowledge/" + id + "/formInteraction/edit/dictionary",
                  query
                  }}>
                  <Button icon="rollback" style={{marginRight:10}}>返回列表</Button>
              </Link>
              <Button style={{marginRight:10}} onClick={this.openImportModal}>Excel导入</Button>
              {
                query.dictionaryId ? <Button style={{marginRight:10}} onClick={this.doExport}>Excel导出</Button> : ''
              }
              
              
              <Button type="primary" onClick={this.saveValidate}>保存</Button>
              
            </div>
          </div>

          <div id="luckysheet" className={styles.luckysheetStyle}></div>
        </Form>

        <Modal
          title="Excel导入"
          visible={importVisible}
          onCancel={this.cancelImportModal}
          footer={[
            <Button onClick={this.cancelImportModal}>取消</Button>,
            <Upload {...importProps}>
              <Button style={{marginLeft:10}} type="primary" loading={importLoading}>Excel导入</Button>
            </Upload>
          ]}
          maskStyle={{zIndex:"1004"}}
          zIndex={1005}
        >
            <p>请按照模板中的示例格式进行编辑上传：<Button type="link" onClick={this.downloadTemplate}>下载导入模板</Button></p>
            <p>上传文件格式需要为“.xlsx”或“.xls”类型的Excel文件</p>
        </Modal>

      </div>
    )
  }

}

export default Form.create()(DictionaryEdit)